//
//  BaseInfoVC.m
//  u76ho
//
//  Created by m-air-01 on 15/12/29.
//  Copyright © 2015年 LV. All rights reserved.
//

#import "BaseInfoVC.h"
#import "BaseInfoFirCell.h"
#import "BaseInfoSecCell.h"
#import "BaseInfoThiTableViewCell.h"
#import "NameViewController.h"
#import "SurePhoneNumViewController.h"
#import "RealNameCertifyVC.h"
#import "ReadBaseInfoModel.h"
#import "MLImageCrop.h"
#import "LoginViewController.h"
#import "FeRollingLoader.h"
@interface BaseInfoVC ()
<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,ChangeNameDelegate,UIActionSheetDelegate,SurePhoneNumDelegate,RealnameDelegate,MLImageCropDelegate,UIAlertViewDelegate>
{
    UITableView * _tabelView;
    NSMutableArray * dataSource;
    
    UIImage * headerImg;
    UIImagePickerController * pickerVC;
    
    ReadBaseInfoModel * myModel;
    ReadBaseInfoModel * firstModel;
    NSString * imgName;
    
    
}
@property (strong, nonatomic) FeRollingLoader *rollingLoader;

@end
#pragma mark - 视图的生命周期
@implementation BaseInfoVC
-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self main];
    
    _rollingLoader = [[FeRollingLoader alloc] initWithView:self.view title:@"LOADING"];
    [self.view addSubview:_rollingLoader];
    
    [_rollingLoader show];
    

    
    self.navigationItem.title =  @"个人信息";
    //[self addBackItem];
    [self addrightItems];
    // Do any additional setup after loading the view.
}
-(void)main
{
    [self.view setBackgroundColor:[UIColor whiteColor]];
    dataSource = [[NSMutableArray alloc]init];
    [dataSource addObjectsFromArray:@[@"头像",@"姓名",@"性别",@"手机号",@"身份证",@"我的公司",@"我的职位"]];
    _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    _tabelView.dataSource = self;
    _tabelView.delegate = self;
    [_tabelView registerNib:[UINib nibWithNibName:@"BaseInfoFirCell" bundle:nil] forCellReuseIdentifier:@"BaseInfoFirCell"];
    [_tabelView registerNib:[UINib nibWithNibName:@"BaseInfoSecCell" bundle:nil] forCellReuseIdentifier:@"BaseInfoSecCell"];
    [_tabelView registerNib:[UINib nibWithNibName:@"BaseInfoThiTableViewCell" bundle:nil] forCellReuseIdentifier:@"BaseInfoThiTableViewCell"];
    [self.view addSubview:_tabelView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self requestData];
}
-(void)requestData
{
    [U76HONet readPeopleInfomationWitnActon:@"" code:[Singleton share].code andDataBlock:^(ReadBaseInfoModel *model) {
        NSLog(@"读取个人信息成功了");
        myModel = model;
        
//        companyname = "\U5feb\U4e50\U5de5\U4f5c";
//        duty = "\U6280\U672f";
//        headpic = 222222;
//        idcard = "";
//        mobile = 222222;
//        qycode = 111111;
//        sex = 1;
//        username = 222222;
        
        
//        companyname = "<null>";
//        duty = "<null>";
//        headpic = "/Uploads/Sysimg/boy.jpg";
//        idcard = "<null>";
//        mobile = 18701534473;
//        qycode = 0;
//        sex = 1;
//        username = "gtugt\U5218";
        
        
        
        NSDictionary * dic = @{@"companyname":myModel.companyname ? myModel.companyname : @"",@"duty":myModel.duty ? myModel.duty : @"",@"headpic":myModel.headpic,@"idcard":myModel.idcard ? myModel.idcard : @"",@"mobile":myModel.mobile,@"qycode":myModel.qycode,@"sex":myModel.sex,@"username":myModel.username};
        firstModel = [[ReadBaseInfoModel alloc]initDic:dic];

        
        [_rollingLoader removeFromSuperview];
        
        [_tabelView reloadData];
    }];
}
-(void)modifyDatawithimgPath:(NSString *)path
{
    __weak typeof(self)weakSelf = self;
    [U76HONet modifyPeopleInfomationwithAction:@"" code:[Singleton share].code mobile:myModel.mobile headpic:path username:myModel.username sex:myModel.sex idcard:myModel.idcard ? myModel.idcard : @"" andDataBlock:^(NSDictionary *dic) {
        NSLog(@"修改用户信息成功列");
        if ([Singleton share].userInformation) {
            NSDictionary * dic = [Singleton share].userInformation;
            
            NSString * isreal;
            if ([[dic objectForKey:@"isreal"] isEqualToString:@"1"]) {
                isreal = @"1";
            }
            else
            {
                if ([firstModel.idcard isEqualToString:myModel.idcard]) {
                    isreal = @"2";
                }
                else
                {
                    isreal = @"1";
                }
            }
            
            NSDictionary * mDic = @{@"code":[dic objectForKey:@"code"],@"headpic":path,@"isreal":isreal,@"mobile":myModel.mobile,@"password":[dic objectForKey:@"password"],@"qycode":[dic objectForKey:@"qycode"],@"username":myModel.username};
            //            {
            //                code = 9f99f793ae03c405ade147fc44e86a93;
            //                headpic = "/Uploads/20160223/1456194353700431.jpg";
            //                isreal = 2;
            //                mobile = 18233028355;
            //                password = e10adc3949ba59abbe56e057f20f883e;
            //                qycode = 0;
            //                username = dawei;
            //            }
            
            
            [Singleton share].userInformation = mDic;
            [[Singleton share] saveUserInformation];
            
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"modifyNameAndHeadpic" object:nil];
        
        [Singleton alerSendMessage:@"修改用户信息成功"];
        [weakSelf performSelector:@selector(backItem:) withObject:nil afterDelay:1];
        

        
    }];
}
-(void)upheaderImg
{
//    [U76HONet upPictureWithaction:@"" pictures:@[tempImg] picname:[NSString stringWithFormat:@"%i.jpg",i] andDataBlock:^(NSDictionary *dic) {
//        NSLog(@"上穿图片成功了");
//        
//        [imgsizeStrArr addObject:[dic objectForKey:@"data"]];
//        [picStrArr addObject:[NSString stringWithFormat:@"%i.jpg",i]];
//        
//        if (imgsizeStrArr.count == myPictureArr.count) {
//            distubuteinfomodel.imgsize = [imgsizeStrArr componentsJoinedByString:@"|"];
//            distubuteinfomodel.pic = [picStrArr componentsJoinedByString:@"|"];
//            
//            [weakSelf distubteInformation];
//        }
//        
//    }];

    NSDate * date = [NSDate date];
    NSInteger dataCH = [date timeIntervalSince1970];
    NSString * dateStr = [NSString stringWithFormat:@"%i",(int)dataCH];
    
    int randanNum = arc4random() % 1000000;
    NSString * tempStr = [NSString stringWithFormat:@"%@%i.jpg",dateStr,randanNum];
    
    imgName = tempStr;
    
    __weak typeof(self)weakSelf = self;
    [U76HONet upPictureWithaction:@"" pictures:@[headerImg] picname:imgName andDataBlock:^(NSDictionary *dic) {
        NSLog(@"上穿图片成功了");
//        {
//            data = "800:500";
//            errcode = 0;
//            fileparth = "/Uploads/20160223/";
//        }
        [weakSelf modifyDatawithimgPath:[NSString stringWithFormat:@"%@%@",[dic objectForKey:@"fileparth"],imgName]];
    }];
}
#pragma  mark - _tabelViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 0:
        {
            BaseInfoFirCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoFirCell"];
            if (myModel!=nil) {
                [cell.headerImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",U76HOURL,myModel.headpic]] placeholderImage:[UIImage imageNamed:@"公司简介成长－默认头像"]];
            }
            if (headerImg!=nil) {
                cell.img = headerImg;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 1:
        {
            BaseInfoSecCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoSecCell"];
            cell.firstLab.text = [dataSource objectAtIndex:indexPath.row];
            if (myModel!=nil) {
                cell.secondLab.text = myModel.username;
            }
            cell.secondLab.tag = 1;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 2:
        {
            BaseInfoSecCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoSecCell"];
            cell.firstLab.text = [dataSource objectAtIndex:indexPath.row];
            if (myModel!=nil) {
                if ([myModel.sex isEqualToString:@"1"]) {
                    cell.secondLab.text = @"男";
                }
                else
                {
                    cell.secondLab.text = @"女";
                }
            }

            cell.secondLab.tag = 2;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 3:
        {
            BaseInfoSecCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoSecCell"];
            cell.firstLab.text = [dataSource objectAtIndex:indexPath.row];
            if (myModel!=nil) {
                cell.secondLab.text = myModel.mobile;
            }

            cell.secondLab.tag = 3;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 4:
        {
            BaseInfoSecCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoSecCell"];
            cell.firstLab.text = [dataSource objectAtIndex:indexPath.row];
            if (myModel!=nil) {
                cell.secondLab.text = myModel.idcard;
            }
            cell.secondLab.tag = 4;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 5:
        {
            BaseInfoThiTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoThiTableViewCell"];
            cell.firstLab.text = [dataSource objectAtIndex:indexPath.row];
            if (myModel!=nil) {
                cell.secondLab.text = myModel.companyname;
            }

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case 6:
        {
            BaseInfoThiTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInfoThiTableViewCell"];
            cell.firstLab.text = [dataSource objectAtIndex:indexPath.row];
            if (myModel!=nil) {
                cell.secondLab.text = myModel.duty;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        default:
            break;
    }
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:@"选择上传图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从本地获取",@"从相册获取",nil];
        [sheet showInView:self.view];
    }
    else if (indexPath.row == 1)
    {
        NameViewController * nameVC = [[NameViewController alloc]init];
        nameVC.delegate = self;
        nameVC.firstName = [dataSource objectAtIndex:indexPath.row];
        if (myModel!=nil) {
            nameVC.firstName = myModel.username;
        }
        
        [self.navigationController pushViewController:nameVC animated:YES];
    }
    else if (indexPath.row == 2)
    {
        UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
        sheet.tag = 712;
        [sheet showInView:self.view];
    }
    else if (indexPath.row == 3)
    {
        SurePhoneNumViewController * phoneNumVC = [[SurePhoneNumViewController alloc]init];
        phoneNumVC.delegate = self;
        [self.navigationController pushViewController:phoneNumVC animated:YES];
    }
    else if (indexPath.row == 4)
    {
        RealNameCertifyVC * realNamecerticifyVC = [[RealNameCertifyVC alloc]init];
        realNamecerticifyVC.delegate = self;
        [self.navigationController pushViewController:realNamecerticifyVC animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
//点击提示框山的按钮 调用设备的相册
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 712) {
        UITextField * textField = (UITextField *)[self.view viewWithTag:2];
        if (buttonIndex == 0) {
            textField.text = @"男";
            myModel.sex = @"1";
        }
        else if (buttonIndex == 1)
        {
            textField.text = @"女";
            myModel.sex = @"2";
        }
    }
    else
    {
        if (buttonIndex == 0) {
            //跳转到设备的相机
            NSLog(@"00000000000");
            pickerVC = [[UIImagePickerController alloc]init];
            [pickerVC setSourceType:UIImagePickerControllerSourceTypeCamera];
            pickerVC.delegate = self;
            [self presentViewController:pickerVC animated:YES completion:nil];
        }
        else if(buttonIndex == 1)
        {
            //跳转到设备的本地库
            NSLog(@"11111111111");
            pickerVC = [[UIImagePickerController alloc]init];
            [pickerVC setSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            pickerVC.delegate = self;
            [self presentViewController:pickerVC animated:YES completion:nil];
        }
        else if(buttonIndex == 2)
        {
            //跳转到设备的相册
            NSLog(@"222222222");
            pickerVC = [[UIImagePickerController alloc]init];
            [pickerVC setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            pickerVC.delegate = self;
            [self presentViewController:pickerVC animated:YES completion:nil];
        }
        if (buttonIndex == 3) {
            NSLog(@"33333333");
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }
    }
    
}
//将选中的图片付给头像
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * selectImg = [info objectForKey:UIImagePickerControllerOriginalImage];

//    headerImg = selectImg;
    
    MLImageCrop *imageCrop = [[MLImageCrop alloc]init];
    imageCrop.delegate = self;
    imageCrop.ratioOfWidthAndHeight = 800.0f/800.0f;
    imageCrop.image = selectImg;
    [imageCrop showWithAnimation:YES];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - crop delegate
- (void)cropImage:(UIImage*)cropImage forOriginalImage:(UIImage*)originalImage
{
//    self.imageView.image = cropImage;
//    self.imageView.frame = CGRectMake(0, 120, self.view.frame.size.width, self.view.frame.size.width*(cropImage.size.height/cropImage.size.width));
    
    headerImg = cropImage;

    [_tabelView reloadData];

}
#pragma mark - 自定义delegate的实现们
-(void)changNameWithStr:(NSString *)name
{
    UILabel * lab = (UILabel *)[self.view viewWithTag:1];
    myModel.username = name;
    lab.text = name;
}
-(void)surephoneNumDelegatewithStr:(NSString *)str
{
    UILabel * lab = (UILabel *)[self.view viewWithTag:3];
    myModel.mobile = str;
    lab.text = str;
}
-(void)realNameDelegateWithIdcard:(NSString *)idcard
{
    UILabel * lab = (UILabel *)[self.view viewWithTag:4];
    myModel.idcard = idcard;
    lab.text = idcard;
}
#pragma mark - addRightItem
-(void)addrightItems
{
    UIButton * saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, 0, 40, 40);
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}
-(void)saveBtnAction:(UIButton *)btn
{
    NSLog(@"保存了*****");
    if ([self isLogin]) {
        
        

        
    __weak typeof(self)weakSelf = self;
    //        companyname = "\U5feb\U4e50\U5de5\U4f5c";
    //        duty = "\U6280\U672f";
    //        headpic = 222222;
    //        idcard = "";
    //        mobile = 222222;
    //        qycode = 111111;
    //        sex = 1;
    //        username = 222222;
    if (headerImg == nil) {
        if ([firstModel.companyname isEqualToString:myModel.companyname] && [firstModel.duty isEqualToString:myModel.duty] && [firstModel.headpic isEqualToString:myModel.headpic] && [firstModel.idcard isEqualToString:myModel.idcard] && [firstModel.mobile isEqualToString:myModel.mobile] && [firstModel.qycode isEqualToString:myModel.qycode] && [firstModel.sex isEqualToString:myModel.sex] && [firstModel.username isEqualToString:myModel.username]) {
            [Singleton alerSendMessage:@"您未做任何修改哦"];
            return;
        }
        [U76HONet modifyPeopleInfomationwithAction:@"" code:[Singleton share].code mobile:myModel.mobile headpic:myModel.headpic username:myModel.username sex:myModel.sex idcard:myModel.idcard ? myModel.idcard : @"" andDataBlock:^(NSDictionary *dic) {
            NSLog(@"**修改用户信息成功列");
            
            if ([Singleton share].userInformation) {
                NSDictionary * dic = [Singleton share].userInformation;
                
                NSString * isreal;
                if ([[dic objectForKey:@"isreal"] isEqualToString:@"1"]) {
                    isreal = @"1";
                }
                else
                {
                    if ([firstModel.idcard isEqualToString:myModel.idcard]) {
                        isreal = @"2";
                    }
                    else
                    {
                        isreal = @"1";
                    }
                }

                
                NSDictionary * mDic = @{@"code":[dic objectForKey:@"code"],@"headpic":[dic objectForKey:@"headpic"],@"isreal":isreal,@"mobile":myModel.mobile,@"password":[dic objectForKey:@"password"],@"qycode":[dic objectForKey:@"qycode"],@"username":myModel.username};
                //            {
                //                code = 9f99f793ae03c405ade147fc44e86a93;
                //                headpic = "/Uploads/20160223/1456194353700431.jpg";
                //                isreal = 2;
                //                mobile = 18233028355;
                //                password = e10adc3949ba59abbe56e057f20f883e;
                //                qycode = 0;
                //                username = dawei;
                //            }
                
                
                [Singleton share].userInformation = mDic;
                [[Singleton share] saveUserInformation];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"modifyNameAndHeadpic" object:nil];
            }

            
            [Singleton alerSendMessage:@"修改用户信息成功"];
            [weakSelf performSelector:@selector(backItem:) withObject:nil afterDelay:1];
        }];
    }
    else
    {
        [self upheaderImg];
    }
        
    }
}
-(BOOL)isLogin
{
    if ([Singleton share].code) {
        NSLog(@"登录了");
        return YES;
        
    }
    else
    {
        //        NSLog(@"还没登录呢");
        //        LoginViewController * loginVC = [[LoginViewController alloc]init];
        //        [self.navigationController pushViewController:loginVC animated:NO];
        //        return NO;
        if (SYSTEM_VERSION >= 8.0) {
            UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还没有登录是否登录" preferredStyle:UIAlertControllerStyleAlert];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                LoginViewController * loginVC = [[LoginViewController alloc]init];
                UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
                nvc.navigationBarHidden = YES;
                [self presentViewController:nvc animated:YES completion:nil];
                
            }]];
            [alerVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }]];
            [self.view.window.rootViewController presentViewController:alerVC animated:YES completion:nil];
            
        }
        else
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您还没有登录是否登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        return NO;
        
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = (int)buttonIndex;
    if (i == 0) {
        
    }
    else if(i == 1)
    {
        LoginViewController * loginVC = [[LoginViewController alloc]init];
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginVC];
        
        nvc.navigationBarHidden = YES;
        [self presentViewController:nvc animated:YES completion:nil];
        
    }
}

#pragma  mark - 返回按钮图标
-(void)addBackItem{
    UIButton * backItem = [UIButton buttonWithType:UIButtonTypeCustom];
    backItem.frame = CGRectMake(0, 0, 9, 17);
    [backItem setImage:[UIImage imageNamed:@"返回图标"] forState:UIControlStateNormal];
    [backItem addTarget:self action:@selector(backItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backItem];
}
-(void)backItem:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
